<?php
$path = '/var/www/wiisocial';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once "services/AWSProxy.php";
require_once "data/dao/GameDAO.php";
require_once "data/dao/SynchronizeLogDAO.php";
require_once "services/MailUtils.php";
require_once "Constants.php";
require_once "conf.php";

/**
 * this script updates the games table, and is executed as a cron job hourly
 */

class GameSynchronizer{

	private $gameLocales;
	// game data access object
	private $game;
	
	public function GameSynchronizer(){

		$this->gameLocales = array(UK_LOCALE, US_LOCALE);
		// game data access object
		$this->game = new GameDAO();
	}

	public function	synchronize(){
		
		$startTime = date("d-m-y:h:m");

		// perform synchronization for each locale		
		foreach($this->gameLocales as $locale){		

			$currentGamesTotal = $this->game->getTotalGames();

			$aws = new AWSProxy();
		
			$addedGames = array();

			foreach($aws->getAllWiiGames($locale) as $g){
			
				// stop duplicate entries appearing from 
				// amazon marketplace
				if((!$this->game->gameExists($g['id'])) && (!in_array($g['id'],$this->getExcludedItemsAsArray()))){
				
					if(!$this->isGameADuplicate($g['title'], $locale)){
						
						array_push($addedGames, $g['title']);
				
						try{
							$this->game->addGame($g['id'], $g['title'], $g['manufacturer'], $g['release_date'], $g['image_url'], 
								$g['largeImageUrl'], $g['amazon_url'], $locale, $g['description'], 0);			
						}
						catch(Exception $e){
							// exception caught
						}
					}
				}
				else{
				
					$gameId = $g['id'];
					if($this->game->gameExists($gameId)){
						
						$game = $this->game->getGame($gameId);
						// updates image url
						if(($game->getImageURL() == null) || ($game->getImageURL() != $g['image_url'])){
							echo "adding image url for " . $g['id'] . "\n";
							$this->game->updateImageUrl($g['id'], $g['image_url']);
						}

						// sometimes the image file is not present on amazons server
						if(!file_get_contents($game->getImageURL())){
							$this->game->updateImageUrl($game->getID(), "");
						}
						
						// updates large image url
						if(($game->getLargeImageURL()) == null || ($game->getLargeImageURL() != $g['largeImageUrl'])){
							echo "adding large image url for " . $g['id'] . "\n";
							$this->game->updateLargeImageUrl($g['id'], $g['largeImageUrl']);
						}

						// sometimes the image file is not present on amazons server
						if(!file_get_contents($game->getLargeImageURL())){
							$this->game->updateLargeImageUrl($game->getID(), "");
						}
						
						
						// updates amazon url
						if($game->getAmazonAssociateURL() == null)
							$this->game->updateAmazonUrl($g['id'], $g['amazon_url']);

						// adds game description
				 		if($game->getDescription() == null)
							$this->game->updateDescription($g['id'], $g['description']);
					}
				}
			}
		}

		$endTime = date("d-m-y:h:m");	

		$this->tidyUpGameList();
		$sl = new SynchronizeLogDAO();
		$sl->logSynchronization($startTime, $endTime, $currentGamesTotal, count($addedGames), $addedGames);
	}
	
	private function sendEmailNotification($start_time, $current_games){
		
		// notify me via email that the synchronization has taken place
		$to = "mattmakins@gmail.com";
		$from = "";
		$subject = "WiiSocial: Synchronization Complete";
		$body = "Start time: " . $start_time . "<br/>" .
				"Current games: " . $current_games . "<br/>" ;
				
		$es = new EmailSender($to, $from, $subject, $body);
		
	}
	
	private function tidyUpGameList(){
		
		$xml = new SimpleXMLElement(file_get_contents(CONF_DIR . "/game.conf.xml"));
		
		foreach($xml->item as $game){
			
			if($this->game->gameExists($game))
				$this->game->deleteGame($game);
		}
	}

	/**
	 * returns an array of excluded items from 
	 * conf/game.conf.xml
	 * 
	 * @return Array String
	 */
	private function getExcludedItemsAsArray(){
		
		$excludedItems = array();
		
		$xml = new SimpleXMLElement(file_get_contents(CONF_DIR . "/game.conf.xml"));
		
		foreach($xml->item as $i){
			
			array_push($excludedItems, $i);
		}
		
		return $excludedItems;
	}
	
	/**
	 * this method checks that the game is not a duplication
	 * of an existing game in database.
	 * 
	 * duplications can come from the amazon market place.
	 * 
	 * if a game already exists with same title, and locale
	 * return true.
	 *
	 */
	private function isGameADuplicate($title, $locale){
		
		$game = $this->game->getGameByTitle($title);
		
		// game doesn't exist
		if($game == null){
			return false;
		}
		
		// game does exist, but in a different locale
		if ($game->getLocale() != $locale){
			return false;
		}
		
		return true;
	}
}
$gs = new GameSynchronizer();
$gs->synchronize();
?>
